package tyk.Service;

import tyk.Dao.BaseDao;
import tyk.pojo.Email;
import tyk.pojo.User;
import tyk.utils.SHA256;

import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/***
 *@title EmailService
 *@description <TODO description class purpose>
 *@author Tang'ya'kang
 *@VERSION 1.0.0
 *@CREATE 2023/5/28 14:13
 **/
public class EmailService extends BaseDao {
    public void insert(Email email) throws SQLException {
        String sql="insert into email (user_name,expiration_time,token) values(?,?,?);";
        super.executeUpdate(sql,email.getUser_name(),email.getExpiration_time(),email.getToken());
    }
    public Integer SelectEmail(String user_name,Integer token) throws SQLException, IllegalAccessException, NoSuchFieldException, InstantiationException {
        String sql="delete from email where expiration_time < NOW();";
        super.executeUpdate(sql);
        sql="select user_name,expiration_time,token from email where user_name = ? and token = ?;";
        List<Email> list=new ArrayList<>();
        System.out.println("到此一游");
        Integer rows= super.executeQuery(sql,user_name,token);
        if(rows>0) {
            sql="delete from email where user_name = ? and token = ?;";
            super.executeUpdate(sql,user_name,token);
        }
        return rows;
    }
    public void EditEmail(String user_name,String ToEmail) throws SQLException {
        String sql="update user set email = ? where username = ?;";
        super.executeUpdate(sql,ToEmail,user_name);
    }
    public List<User> SelectByEmail(String email) throws SQLException, IllegalAccessException, NoSuchFieldException, InstantiationException {
        String sql="select id,username,password,email from user where email = ?;";
        System.out.println(email);
        return super.executeQuery(User.class,sql,email);
    }
    public void SuccessPassword(String user_name,String password) throws NoSuchAlgorithmException, SQLException {
        String sql="update user set password = ? where username = ?;";
        password= SHA256.hash(password,user_name.getBytes());
        password= SHA256.hash(password,user_name.getBytes());
        executeUpdate(sql,password,user_name);
    }
}
